<template>
	<view class="knowledge">
		<view v-if="!searchLoading">
			<view v-if="fileList && fileList.length > 0">
				<scroll-view @scrolltolower="nextPage" @refresherrefresh="refresh" refresher-enabled :refresher-triggered="isRefreshing" scroll-y
					:style="{height: 'calc(100vh - 140rpx - ' + safeAreaInsetBottom + 'px)'}">
					<view class="file-list">
						<view class="file-item" v-for="(item, index) in fileList" :key="item.id">
							<view class="file-info">
								<view class="flex">
									<u-icon name="file-text" size="20" color="#2979ff"></u-icon>
									<view class="file-name">
										<u--text :lines="1" :text="item.name"></u--text>
									</view>
								</view>
								<view class="status" :class="{
							    'status-success': item.run === 'DONE',
							    'status-processing': item.run === 'UNSTART',
							    'status-processing': item.run === 'RUNNING',
							    'status-error': item.run === 'error'
							  }">
									{{ getStatusText(item.run) }}
								</view>
							</view>
							<view class="file-meta">
								<view class="upload-time">
									{{ item.create_date ? formatDate(new Date(item.create_date)) : "" }}</view>
								<view class="flex">
									<view>
										<u-icon name="trash" size="20" color="#fa3534"
											@click="deleteFile(item, index)"></u-icon>
									</view>
								</view>
							</view>
						</view>
					</view>
					<u-loadmore :status="loadMoreStatus" />
				</scroll-view>
			</view>
			<view v-else class="flex align-center justify-center"
				:style="{height: 'calc(100vh - 140rpx - ' + safeAreaInsetBottom + 'rpx)'}">
				<u-empty mode="search"></u-empty>
			</view>
		</view>
		<view v-else class="pt-20">
			<u-skeleton rows="30" :title="false" :loading="searchLoading"></u-skeleton>
		</view>
		<!-- 底部上传按钮（考虑安全区域） -->
		<view class="upload-btn-container safe-area-inset-bottom">
			<u-button type="primary" shape="circle" icon="plus" @click="uploadFile">
				上传文件
			</u-button>
		</view>
		<u-notify ref="errorMsgNotify" :message="errorMsg"></u-notify>
		<u-modal @confirm="delConfirmBtnClick" @cancel="modalVisible = false"
			@close="modalVisible = false" :show="modalVisible" :showCancelButton="true"
			:closeOnClickOverlay="true" title="提示" content="确定要删除这个文件吗">
		</u-modal>
		<u-toast ref="toast"></u-toast>
	</view>
</template>

<script>
	import api from "@/api/api";
	export default {
		data() {
			return {
				safeAreaInsetBottom: 0,
				fileList: [],
				page: 1,
				size: 10,
				errorMsgVisible: false,
				errorMsg: "",
				searchLoading: true,
				loadMoreStatus: "loadmore",
				apiKey: null,
				knowledgeBase: null,
				modalVisible: false,
				selectedFile: null,
				selectedFileIndex: null,
				isRefreshing: false
			}
		},
		async onLoad() {
			let safeAreaInsets = uni.getSystemInfoSync().safeAreaInsets;
			this.safeAreaInsetBottom = safeAreaInsets.bottom;
			await this.loadKnowledgeBase();
			if (this.apiKey && this.knowledgeBase && this.knowledgeBase.knowledgeBaseId) {
				this.loadKnowledge();
			} else {
				this.searchLoading = false;
			}
		},
		onShow() {},
		methods: {
			async loadKnowledgeBase() {
				let knowledgeBase = await this.depot.get(api.aiCard(
					"ragflowKnowledgebase/findByChatAssistantTypeAndType?chatAssistantType=AI_CARD&type=DEFAULT"
					))
				knowledgeBase = knowledgeBase && knowledgeBase.data && knowledgeBase.data.data ? knowledgeBase.data
					.data : null;
				this.knowledgeBase = knowledgeBase;
				this.apiKey = knowledgeBase && knowledgeBase.ragflowUser ? knowledgeBase.ragflowUser.apiKey : null;
			},
			loadKnowledge() {
				let url = "datasets/" + this.knowledgeBase.knowledgeBaseId + "/documents?page=" +
					this.page + "&size=" + this.size;
				let header = {
					Authorization: "Bearer " + this.apiKey
				}
				this.depot.get(api.ragflow(url), null, header).
				then(response => {
					this.isRefreshing = false
					this.$nextTick(() => { this.isRefreshing = false })
					if (response && response.data && response.data.data) {
						if (response.data.data.docs && response.data.data.docs.length) {
							if (response.data.data.docs.length < this.size) {
								this.loadMoreStatus = "nomore"
							} else {
								this.loadMoreStatus = "loadmore"
							}
						} else {
							this.loadMoreStatus = "nomore"
						}
						this.fileList = this.fileList.concat(response.data.data.docs);
					}
				}).finally(() => {
					this.searchLoading = false;
				})
			},
			nextPage() {
				this.page++;
				this.loadMoreStatus = "loading";
				this.loadKnowledge();
			},
			refresh() {
				this.page = 1;
				this.fileList = [];
				this.loadMoreStatus = "loading";
				this.loadKnowledge();
			},
			companyInfoClick(companyInfo) {
				if (companyInfo && companyInfo.companyInfoId) {
					uni.navigateTo({
						url: "/pages/companySearch/companyInfo?companyInfoId=" + companyInfo.companyInfoId
					})
				}
			},
			// 上传文件
			uploadFile() {
				let knowledgeBaseId = this.knowledgeBase.knowledgeBaseId;
				if (!knowledgeBaseId || !this.apiKey) {
					console.log("知识库信息未加载");
					return;
				}
				uni.chooseMessageFile({
					count: 1,
					type: 'all',
					success: async (res) => {
						const tempFile = res.tempFiles[0];
						console.log(tempFile.name)
						this.$u.toast('文件上传中...');

						try {
							//上传
							let header = {
								Authorization: "Bearer " + this.apiKey
							}
							const uploadRes = await this.depot.uploadFile(api.ragflow("datasets/" +
								knowledgeBaseId + "/documents"), tempFile.path, header);
							let documentInfo = uploadRes && uploadRes.data && uploadRes.data.length ? uploadRes
								.data[0] : null;
							if (documentInfo && documentInfo.id) {
								// 文件名称是随机字符串， 需要更新文件名称
								await this.depot.put(api.ragflow("datasets/" + knowledgeBaseId +
									"/documents/" + documentInfo.id), {
									"name": tempFile.name
								}, header)
								documentInfo.name = tempFile.name;
								// 添加到列表顶部
								this.fileList.unshift(documentInfo);
								//TODO 启动文件解析并且绑定知识库到聊天助手
								//开始文件解析
								let documentIds = [documentInfo.id];
								await this.depot.post(api.ragflow("datasets/" + knowledgeBaseId +
									"/chunks"), {
									"document_ids": documentIds
								}, header)
							}
							this.$u.toast('上传成功');
						} catch (e) {
							console.error(e);
							this.$u.toast('上传失败');
						}
					}
				});
			},
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					DONE: '解析成功',
					UNSTART: '解析中',
					RUNNING: '解析中',
					error: '解析失败'
				};
				return statusMap[status] || '未知状态';
			},
			// 删除文件
			deleteFile(fileInfo, index) {
				this.selectedFile = fileInfo;
				this.selectedFileIndex = index;
				this.modalVisible = true;
			},
			async delConfirmBtnClick() {
				this.modalVisible = false;
				let id = this.selectedFile && this.selectedFile.id ? this.selectedFile.id : null;
				if (!id) {
					return;
				}
				let header = {
					Authorization: "Bearer " + this.apiKey
				}
				await this.depot.delete(api.ragflow("datasets/" + this.knowledgeBase.knowledgeBaseId +
					"/documents"), {
					"ids": [id]
				}, header)
				this.fileList.splice(this.selectedFileIndex, 1)
					
				this.$refs.toast.show({
					type: "success",
					title: "提示",
					message: "文件删除成功"
				});
				
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			}
		}
	}
</script>

<style lang="less" scoped>
	.knowledge {
		min-height: 100vh;
		background-color: #fff;

		&-top {
			height: 476rpx;
			background: url(https://biz-miniapp.oss-cn-beijing.aliyuncs.com/newVersionImg/topBgc.png) no-repeat;
			background-size: 100% 100%;
			position: relative;

			&-sty {
				height: 88rpx;
			}

			&-title {
				position: fixed;
				left: 0;
				width: 100%;
				padding: 0 30rpx;
				line-height: 80rpx;
				color: #fff;
				z-index: 20;

				text {
					display: inline-block;
					width: 30rpx;
				}

				view {
					font-weight: bold;
				}
			}

			&-search {
				line-height: 68rpx;
				border-radius: 34rpx;
				border-color: #333;
				padding: 0rpx 16rpx;
				margin: 0rpx 10rpx;

				input {
					color: #666;
					flex: 1;
					margin: 15rpx 20rpx;
				}

				&-pla {
					color: #999;
				}

				button {
					width: 100rpx;
					line-height: 50rpx;
					background: linear-gradient(153deg, #5c8df7 0%, #2f54eb 100%);
					border-radius: 25rpx;
					color: #fff;
				}
			}
		}

		&-history {
			padding-left: 20rpx;
			margin-top: 20rpx;

			&-title {
				font-size: 28rpx;
				color: #fff;
			}

			/deep/.u-tag--primary--plain {
				border-color: #fff;
			}

			/deep/.u-tag__text--primary--plain {
				color: #fff;
			}
		}

		&-total {
			padding: 20rpx;
			color: #333;
			background-color: #fff;
			border-bottom: 1rpx solid #e6e6e6;
		}

		&-list {
			padding: 25rpx;
			border-bottom: 1rpx solid #e6e6e6;

			&-title {
				button {
					width: 100rpx;
					line-height: 50rpx;
					background: rgba(26, 108, 255, 0.1);
					border-radius: 25rpx;
					color: #2f54eb;
					font-weight: bold;
				}

				&-name {
					color: #333;
				}
			}

			&-label {
				color: #999;

				>text {
					display: inline-block;
					padding: 0 20rpx;
					border-right: 1rpx solid #e6e6e6;

					&:last-child {
						border-right: 0;
					}

					&:first-child {
						padding-left: 0;
					}
				}
			}

			&-tel {
				color: #666;
			}

			&-user {
				color: #666;
			}
		}
	}

	.file-list {
		padding: 20rpx 20rpx 0rpx 20rpx;

		.file-item {
			padding: 20rpx;
			margin-bottom: 20rpx;
			background-color: #fff;
			border-radius: 12rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

			.file-info {
				flex: 1;
				display: flex;
				flex-wrap: wrap;
				align-items: center;
				justify-content: space-between;

				.file-name {
					font-size: 28rpx;
					color: #333;
					width: calc(100vw - 250rpx);
				}

				.status {
					padding: 4rpx 12rpx;
					border-radius: 20rpx;
					font-size: 22rpx;
					text-align: center;

					&-success {
						background-color: #e1f3d8;
						color: #67c23a;
					}

					&-processing {
						background-color: #fdf6ec;
						color: #e6a23c;
					}

					&-error {
						background-color: #fde2e2;
						color: #f56c6c;
					}
				}
			}

			.file-meta {
				display: flex;
				justify-content: space-between;
				align-items: baseline;
				font-size: 24rpx;
				margin-top: 20rpx;

				.upload-time {
					color: #999;
					margin-bottom: 8rpx;
				}
			}
		}
	}

	.upload-btn-container {
		padding: 20rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);

		/deep/ .u-btn {
			height: 80rpx;
		}
	}

	.safe-area-inset-bottom {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}
</style>